<template>
  <div v-if="show" class="sidebar-mask" @click.self="close">
    <div class="sidebar">
      <div class="avatar-box">
        <!-- <el-avatar
          :src="avatarUrl"
          size="large"
          shape="square"
          class="avatar-img"
        /> -->
        <img src="@/assets/character.png" class="avatar-img" />
      </div>
      <h2 class="sidebar-title">个人信息</h2>
      <div class="form-item">
        <label>用户名</label>
        <div class="user-name-text">{{ user.name }}</div>
      </div>
      <div class="form-item">
        <label>性格关键词</label>
        <div class="tag-list">
          <span v-if="loading">加载中...</span>
          <span v-else-if="error">{{ error }}</span>
          <template v-else>
            <span v-for="tag in user.tags" :key="tag" class="tag">{{
              tag
            }}</span>
          </template>
        </div>
      </div>
      <div class="form-item">
        <label>MBTI</label>
        <span class="tag">{{ user.mbti }}</span>
      </div>
      <div class="btn-row">
        <button class="primary" @click="close">关闭</button>

        <button class="danger-btn" @click="logout">退出登录</button>
      </div>
      <div class="desc-tip">
        温馨提示：您好！当前mbti和性格标签根据您提供的行为数据动态生成，结果不代表绝对人格定义，仅作为性格特征的参考方向。
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  defineProps,
  defineEmits,
  computed,
  watch,
  getCurrentInstance,
} from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
// import { userApi } from '@/api/user.js'
const defaultAvatar = "@/assets/character.png";
const props = defineProps<{ show: boolean }>();
const emit = defineEmits(["close", "logout"]);
const router = useRouter();
const avatarUrl = ref(defaultAvatar);
const instance = getCurrentInstance();

// 从sessionStorage获取用户信息
const userInfo = ref(JSON.parse(sessionStorage.getItem("userInfo") || "{}"));
const token = ref(sessionStorage.getItem("token") || "");

// 监听sessionStorage变化（跨页面同步）
window.addEventListener("storage", (e) => {
  if (e.key === "userInfo") {
    userInfo.value = JSON.parse(e.newValue || "{}");
  }
  if (e.key === "token") {
    token.value = e.newValue || "";
  }
});

// 监听同页面内的sessionStorage变化
const originalSetItem = sessionStorage.setItem;
sessionStorage.setItem = function (key: string, value: string) {
  const event = new CustomEvent("sessionStorageChange", {
    detail: { key, newValue: value },
  });
  window.dispatchEvent(event);
  originalSetItem.apply(this, [key, value]);
};

window.addEventListener("sessionStorageChange", (e: any) => {
  if (e.detail.key === "userInfo") {
    userInfo.value = JSON.parse(e.detail.newValue || "{}");
  }
  if (e.detail.key === "token") {
    token.value = e.detail.newValue || "";
  }
});

const user = reactive({
  name: computed(() => userInfo.value?.username || "游客"),
  mbti: "INFP",
  tags: ["温和", "细心", "乐观"],
});

const loading = ref(false);
const error = ref("");

async function fetchUserTag(name: string) {
  if (!name || name === "游客") {
    user.mbti = "INFP";
    user.tags = ["温和", "细心", "乐观"];
    return;
  }
  loading.value = true;
  error.value = "";
  try {
    // 尝试使用实际的API获取用户标签
    // @ts-ignore
    const agentAxios = instance?.proxy?.$agentAxios;

    if (agentAxios) {
      console.log("UserSidebar - 调用API获取用户标签:", name);
      const res = await agentAxios.get(`/user_tag/${encodeURIComponent(name)}`);
      const data = res.data;
      user.mbti = data.mbti || "INFP";
      user.tags = data.tag ? data.tag.split(",") : ["温和", "细心", "乐观"];
      console.log("UserSidebar - API返回数据:", data);
    } else {
      console.log("UserSidebar - agentAxios不可用，使用默认数据");
      // 如果agentAxios不可用，使用默认数据
      user.mbti = "INFP";
      user.tags = ["温和", "细心", "乐观"];
    }
  } catch (e) {
    console.error("UserSidebar - 获取用户标签失败:", e);
    error.value = "获取性格数据失败";
    user.mbti = "INFP";
    user.tags = ["温和", "细心", "乐观"];
  } finally {
    loading.value = false;
  }
}

watch(
  () => props.show,
  (val) => {
    if (val) fetchUserTag(user.name);
  }
);
watch(
  () => user.name,
  (val) => {
    if (props.show) fetchUserTag(val);
  }
);

function close() {
  emit("close");
}

function goToUserCenter() {
  console.log("UserSidebar - 跳转到个人中心");
  close();
  router.push("/userCenter");
}

function save() {
  console.log("UserSidebar - 保存用户信息");
  // 显示成功提示
  ElMessage.success("保存成功！");
  close();
}

function logout() {
  console.log("UserSidebar - 处理登出");
  // 清除所有sessionStorage数据
  sessionStorage.removeItem("token");
  sessionStorage.removeItem("userInfo");
  sessionStorage.removeItem("menuList");

  // 触发父组件的logout事件
  emit("logout");
}
</script>

<style scoped>
.sidebar-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(30, 34, 44, 0.1);
  z-index: 2000;
  display: flex;
  justify-content: flex-end;
}
.sidebar {
  width: 340px;
  background: #fff;
  height: 100%;
  box-shadow: none;
  padding: 36px 28px 24px 28px;
  border-radius: 12px 0 0 12px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  position: relative;
}
.avatar-box {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 12px;
  width: 100%;
}
.avatar-img {
  margin-bottom: 8px;
  border-radius: 14px;
  border: 2px solid #d1d5db;
  width: 72px;
  height: 72px;
  box-shadow: none;
}
.sidebar-title {
  text-align: left;
  font-size: 20px;
  font-weight: 600;
  color: #23272f;
  margin-bottom: 18px;
  letter-spacing: 0.5px;
  width: 100%;
  padding-left: 2px;
}
.form-item {
  margin-bottom: 16px;
  display: block;
  width: 100%;
}
.form-item label {
  display: block;
  width: auto;
  color: #444;
  font-weight: 500;
  font-size: 15px;
  letter-spacing: 0.5px;
  text-align: left;
  margin-bottom: 6px;
}
.user-name-text {
  font-size: 16px;
  color: #23272f;
  font-weight: 600;
  padding: 7px 0 7px 0;
  word-break: break-all;
}
.form-item .plain-btn {
  margin-left: 0;
  margin-top: 8px;
  padding: 7px 10px;
  height: 34px;
  display: inline-block;
}
.btn-row {
  margin-top: 10px;
  display: flex;
  gap: 10px;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
}
button.primary {
  background: #23272f;
  color: #fff;
  border: none;
  padding: 7px 22px;
  border-radius: 6px;
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  box-shadow: none;
  transition: background 0.2s;
}
button.primary:hover {
  background: #111;
}
button.plain-btn {
  background: #fff;
  color: #444;
  border: 1px solid #e0e0e0;
  font-size: 15px;
  font-weight: 500;
  padding: 7px 14px;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.2s, border 0.2s;
}
button.plain-btn:hover {
  background: #f5f5f5;
  border: 1px solid #bdbdbd;
}
button.danger-btn {
  background: #fff;
  color: #23272f;
  border: 1px solid #e0e0e0;
  font-size: 15px;
  font-weight: 500;
  padding: 7px 14px;
  border-radius: 6px;
  cursor: pointer;
  margin-left: auto;
  transition: background 0.2s, border 0.2s, color 0.2s;
}
button.danger-btn:hover {
  background: #23272f;
  color: #fff;
  border: 1px solid #23272f;
}
.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.tag {
  display: inline-block;
  background: #f0f1f3;
  color: #444;
  border-radius: 12px;
  padding: 3px 12px;
  font-size: 14px;
  margin-right: 4px;
  margin-bottom: 2px;
  font-weight: 500;
  letter-spacing: 0.5px;
}
.desc-tip {
  color: #888;
  font-size: 13px;
  line-height: 1.7;
  padding-left: 2px;
  width: 80%;
  text-align: left;
  position: absolute;
  left: 50px;
  bottom: 80px;
  padding-right: 0;
}
</style>
